//
//  KLRadioButton.m
//  Launch
//
//  Created by Tommy on 15/4/15.
//  Copyright (c) 2015年 com.taobao. All rights reserved.
//

#import "KLRadioButton.h"

@implementation KLRadioButton


- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        [self p_setupButtons];
        [self configure];
    }
    
    return self;
}



- (void)awakeFromNib{
    [self p_setupButtons];
    [self configure];
}

- (void)configure{

}

- (void)p_setupButtons{
    [self chainButtons];
    if(![[self allTargets] containsObject:self]) {
        [super addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
    }
}


- (void)chainButtons
{
    if ([self.otherButtons count] > 0) {
        for (KLRadioButton *radioButton in self.otherButtons) {
            NSMutableArray *otherButtons = [[NSMutableArray alloc] initWithArray:self.otherButtons];
            [otherButtons addObject:self];
            [otherButtons removeObject:radioButton];
            [radioButton setOtherButtons:[otherButtons copy]];
        }
    }
}

- (void)touchDown
{
    [self setSelected:YES];
}

#pragma mark - UIView




#pragma mark - DLRadiobutton

- (void)deselectOtherButtons
{
    if ([self.otherButtons count] > 0) {
        for (UIButton *button in self.otherButtons) {
            [button setSelected:NO];
        }
    }
}

- (KLRadioButton *)selectedButton
{
    if (self.selected) {
        return self;
    } else {
        for (KLRadioButton *radioButton in self.otherButtons) {
            if (radioButton.selected) {
                return radioButton;
            }
        }
        return nil;
    }
}

#pragma mark - UIControl

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    if (selected) {
        [self deselectOtherButtons];
    }
}



@end
